<?php

declare(strict_types=1);

namespace app\shop\controller\admin\commission;

use sheep\controller\Backend;
use app\shop\model\commission\CommissionGoods as CommissionGoodsModel;
use app\shop\model\goods\Goods as GoodsModel;
use sheep\controller\traits\Crud;
use think\Request;
use think\Response;
use think\facade\Db;

class Goods extends Backend
{
    use Crud;
    protected $model = null;
    protected $isPaginate = true;

    public function initialize()
    {
        $this->model = new CommissionGoodsModel();
    }

    public function list(Request $request): Response
    {
        $data = GoodsModel::sheepFilter()->with('commission_goods')->paginate($request->param('list_rows', 10));
        return success('分销商品列表', $data);
    }

    /**
     * 详情
     *
     * @param  $id
     * @return \think\Response
     */
    public function detail($id)
    {
        $goodsList = GoodsModel::with(['commission_goods'])->whereIn('id', $id)->select()->each(function ($goods) {
            $goods->skus = $goods->skus;
            $goods->sku_prices = $goods->sku_prices;
        });

        $config = sheep_config('shop.commission');
        return success('分销商品详情', [
            'goods' => $goodsList,
            'config' => $config
        ]);
    }

    /**
     * 编辑(支持批量)
     *
     * @param  $id
     * @return \think\Response
     */
    public function edit(Request $request, $id)
    {
        // 接受全部参数
        $params = $request->only(['status', 'self_rules', 'commission_order_status', 'commission_config', 'commission_rules']);

        $result = Db::transaction(function () use ($id, $params) {
            $count = 0;
            $ids = explode(',', $id);
            foreach ($ids as $id) {
                if ($row = $this->model->find($id)) {
                    $row->save($params);
                } else {
                    $params['goods_id'] = $id;
                    $this->model->create($params);
                    unset($params['goods_id']);
                }
                $count++;
            }
            return $count;
        });

        if ($result) {
            return success('更新成功', $result);
        } else {
            return error('更新失败');
        }
    }
}
